package vip.bblog.cunadmin.modules.system.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.bblog.cunadmin.annotation.group.Default;
import vip.bblog.cunadmin.annotation.group.Update;
import vip.bblog.cunadmin.aopConfig.Log;
import vip.bblog.cunadmin.common.entity.BaseResult;
import vip.bblog.cunadmin.common.entity.PageResult;
import vip.bblog.cunadmin.modules.system.dto.ProjectParams;
import vip.bblog.cunadmin.modules.system.entity.Card;
import vip.bblog.cunadmin.modules.system.service.CardService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p> 卡号 * </p>
 *
 * @author yy
 *
 */
@Api(tags = "web:卡号")
@ApiSort(1)
@RestController
@RequestMapping("/card")
public class CardController {

    @Autowired
    private CardService branchService;

    @ApiOperation(value = "分页查询")
    //@PreAuthorize("hasAnyAuthority('sys:card:list')")
    @GetMapping
    public PageResult<List<Card>> listPage(ProjectParams params) {
        return branchService.listPage(params);
    }


    @Log(content = "添加卡号",handleType = "1")
    @ApiOperation(value = "添加卡号")
    @PreAuthorize("hasAnyAuthority('sys:card:add')")
    @PostMapping
    public BaseResult<Card> add(@Validated(Default.class) @RequestBody Card info) {
        branchService.addCard(info);
        return BaseResult.success(info);
    }

    @Log(content = "修改卡号",handleType = "2")
    @ApiOperation(value = "修改")
    @PreAuthorize("hasAnyAuthority('sys:card:update')")
    @PutMapping
    public BaseResult<Card> edit(@Validated(Update.class) @RequestBody Card info) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ctime = formatter.format(new Date());
        info.setCreateTime(ctime);
        branchService.updateById(info);
        return BaseResult.success(info);
    }

    @Log(content = "卡号管理",handleType = "3")
    @ApiOperation(value = "刪除信息")
    @PreAuthorize("hasAnyAuthority('sys:card:delete')")
    @DeleteMapping("{id}")
    public BaseResult<Card> delete(@PathVariable Integer id) {
        branchService.removeById(id);
        return BaseResult.success();
    }

    /**
     * 表格导入
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/importExcel")
    public BaseResult excelImport(@RequestParam("file") MultipartFile file) throws Exception {
        branchService.saveAll(file);
        return BaseResult.success();
    }

    /**
     * 导出Excel
     * @param params
     * @param response
     * @return
     */
    @PostMapping(value="exportExcel")
    @ResponseBody
    public void exportorders(@RequestBody @Validated ProjectParams params,
                             HttpServletRequest request, HttpServletResponse response){
        // 获取workbook对象
        // 单sheet或多sheet 只需要更改此处即可
        Workbook workbook = exportSheets(params) ;
        // 判断数据
        if(workbook == null) {
        }
        // 设置excel的文件名称
        String excelName = "卡号管理" ;
        // 重置响应对象
        response.reset();
        // 当前日期，用于导出文件名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = "["+excelName+"-"+sdf.format(new Date())+"]";
        // 指定下载的文件名--设置响应头
        response.setHeader("Content-Disposition", "attachment;filename=" +dateStr+".xls");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // 写出数据输出流到页面
        try {
            OutputStream output = response.getOutputStream();
            BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
            workbook.write(bufferedOutPut);
            bufferedOutPut.flush();
            bufferedOutPut.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 多sheet导出
     * @return
     */
    public Workbook exportSheets(ProjectParams params){
        params.setPage(1);
        params.setPageSize(1000000);
        //获得日结列表
        PageResult<List<Card>> result = branchService.listPage(params);

        // 创建参数对象（用来设定excel得sheet得内容等信息）
        ExportParams params1 = new ExportParams() ;
        // 设置sheet得名称
        params1.setSheetName("营业收支明细"); ;

        // 创建sheet1使用得map
        Map<String,Object> dataMap1 = new HashMap<>();
        // title的参数为ExportParams类型，目前仅仅在ExportParams中设置了sheetName
        dataMap1.put("title",params1) ;
        // 模版导出对应得实体类型
        dataMap1.put("entity", Card.class) ;
        // sheet中要填充得数据
        dataMap1.put("data",result.getData()) ;

        // 将sheet1和sheet2使用得map进行包装
        List<Map<String, Object>> sheetsList = new ArrayList<>() ;
        sheetsList.add(dataMap1);
        // 执行方法
        return ExcelExportUtil.exportExcel(sheetsList, ExcelType.HSSF) ;
    }

}

